"""
@author: zjc
@file: 三乐购物.py
@time: 2022/11/18 11:21
"""
import json
import os
#1、登录
#2、注册
# user = [["sc","123456",100],["sc1","sc123",200]]
#用户信息： 用户名 密码  余额
#商品信息： 价格 名字  编号
products = [["苹果", 5],["香蕉", 3], ['葡萄', 8], ["榴莲", 40]]
#购物车： 用户名 商品编号 数量
#car={“sc”:[[0, 2], [1, 3]]}

#登录
def login(name, passwd):
    with open("客人信息.txt","r")as fp:
        result=fp.read()
        user_new=json.loads(result)
    if name in user_new and passwd == user_new[name]['passwd']:
        return True

#注册
def register(name,passwd,money):
    if os.path.getsize("客人信息.txt")!=0:
        with open("客人信息.txt","r",encoding="utf8")as fp:
            user_new=json.loads(fp.read())
        if name in user_new:
            print("用户已被注册,请重新输入用户名!")
        else:
            user_new[name]={"passwd":passwd,"money":int(money)}
            user1=json.dumps(user_new)
            with open("客人信息.txt","a+",encoding="utf8")as fp:
                fp.write(user1)
            print("注册成功!")
    else:
        user_new={}
        user_new[name] = {"passwd": passwd, "money": int(money)}
        user1 = json.dumps(user_new)
        with open("客人信息.txt", "a+", encoding="utf8")as fp:
            fp.write(user1)
        print("注册成功!")

#展示商品
def show_goods():
    print("编号".ljust(10, " "), "名称".ljust(10, " "), "价格".ljust(10, " "))
    for index, pro in enumerate(products):
        print(str(index).ljust(11, " "),pro[0].ljust(10," "),str(pro[1]).ljust(10, " "))

#添加商品到购物车
def add_car(name, product_id, nums):
    # car={“sc”:[[0, 2], [1, 3]]}
    if os.path.getsize("购物车.txt")!=0:
        with open("购物车.txt", "r", encoding="utf8")as fp:
            car_new=json.loads(fp.read())
            if name not in car_new:
                car_new[name] = []
                car_new[name].append([product_id, nums])
                print(car_new[name])
                car_new1 = json.dumps(car_new)
                with open("购物车.txt", "w", encoding="utf8")as fp:
                    fp.write(car_new1)
            else:
                car_new[name].append([product_id, nums])
                print(car_new[name])
                car_new1 = json.dumps(car_new)
                with open("购物车.txt", "w", encoding="utf8")as fp:
                    fp.write(car_new1)
    else:
        car_new={}
        car_new[name] = []
        car_new[name].append([product_id, nums])
        print(car_new)
        car_new1 = json.dumps(car_new)
        with open("购物车.txt", "a+", encoding="utf8")as fp:
            fp.write(car_new1)

#查看购物车
def my_shopping_car(name):
    with open("购物车.txt","r")as fp:
        car=json.loads(fp.read())
        print(f"用户 {name} 的 购物车为 {car[name]}")

#结算
def checkout(name):
    #user = {"sc": {"passwd": "123456", "money": 0}}
    with open("客人信息.txt","r")as fp:
        user_new=json.loads(fp.read())
    m1 = user_new[name]["money"]  #用户的钱
    with open("购物车.txt")as fp:
        car=json.loads(fp.read())
    car_list = car[name]  #[[0, 2], [1, 3]]
    # car={“sc”:[[0, 2], [1, 3]]}
    #products = [["苹果", 5], ["香蕉", 3], ['葡萄', 8], ["榴莲", 40]]
    total = 0
    print("编号  ", "名称  ", "单价  ", "数量  ", "总价")
    for pro in car_list:
        #pro -->[1, 3] #[商品编号， 商品数量]
        pro_name = products[pro[0]][0]
        price = products[pro[0]][1]
        pro_total = price * pro[1]
        total += pro_total
        print(f" {pro[0]}    {pro_name}    {price}      {pro[1]}     "
              f"{pro_total}")
    print("所有商品总价为：", total)
    if m1 >= total:
        m1 -= total
    else:
        print("余额不足！")
        money=int(input("请输入充值金额:"))
        add_money(name,money)
        with open("客人信息.txt", "r")as fp:
            user_new = json.loads(fp.read())
        m1 = user_new[name]["money"]  # 用户的钱
        m1-=total
    #修改用户金额
    user_new[name]["money"] = m1
    print(f"用户 {name} 剩余金额:",user_new[name]["money"])
    user1 = json.dumps(user_new)
    with open("客人信息.txt", "w", encoding="utf8")as fp:
        fp.write(user1)

#充值金额
def add_money(name,money):
    with open("客人信息.txt","r")as fp:
        user=json.loads(fp.read())
    user[name]["money"]+=money
    user_new=json.dumps(user)
    with open("客人信息.txt","w")as fp:
        fp.write(user_new)
    print("充值成功!")


#清空购物车
def del_car(name):
    with open("购物车.txt","r",encoding="utf8")as fp:
        car=json.loads(fp.read())
    car[name]=[]
    car_new=json.dumps(car)
    with open("购物车.txt","w",encoding="utf8")as fp:
        fp.write(car_new)
    print("购物车已清空")


#菜单
def menu():
    print("*"*20)
    print("1、查看商品列表")
    print("2、添加到购物车")
    print("3、结算")
    print("4、我的购物车")
    print("5、退出")

print("欢迎来到三乐购物系统".center(50,"*"))
while 1:
    print("1.登录")
    print("2.注册")
    options = input("请输入你的选择(按q退出)：")
    if options == "1":
        name = input("请输入用户名:")
        passwd = input("请输入密码:")
        if login(name, passwd):
            while 1:
                menu()
                op = input("请输入你的操作:")
                if op == "1":
                    show_goods()
                elif op == "2":
                    product_id = input("请输入添加到购物车的商品编号：")
                    if product_id.isdigit() and 0<=int(product_id)<len(products):
                        nums = int(input("请输入需要购买的数量:"))
                        add_car(name, int(product_id), nums)
                elif op == "3":
                    checkout(name)
                    del_car(name)
                elif op=="4":
                    my_shopping_car(name)
                elif op == "5":
                    break
        else:
            print("登录失败！ 用户名或密码错误！")
    elif options == "2":
        name=input("请输入用户名:")
        passwd=input("请输入密码:")
        money=input("请输入金额:")
        register(name,passwd,money)
    elif options == "q":
        break
    else:
        print("输入不合法！")